package com.zking.exeption;

import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerExceptionResolver;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.sql.SQLException;
import java.text.ParseException;

@Component
public class MyExceptionHandler implements HandlerExceptionResolver {
    /*
    实际开发中，会自定义很多异常：
        1. 转换异常
        2. 参数异常
        3. 权限异常
        4. 网络异常
        5. 未知错误……
     */
    @Override
    public ModelAndView resolveException(HttpServletRequest request,
                                         HttpServletResponse response,
                                         Object handler, Exception ex) {
        ModelAndView modelAndView = new ModelAndView();
        if (ex instanceof ParseException) {
            // 转换异常
            modelAndView.setViewName("error");
        } else if (ex instanceof SQLException) {
            // SQL语句异常
            modelAndView.addObject("error", "数据库异常");
            modelAndView.setViewName("error");
        } else {
            modelAndView.addObject("error", "未知异常");
            modelAndView.setViewName("error");
        }
        return modelAndView;
    }
}
